<template>
    <div>
        <!-- 输入栏和按钮 -->
        <div style=" line-height: 40px;margin-bottom: 4px;height: 40px;">
            <el-input style="width: 220px; float: left;margin-left: 5px;" placeholder="请输入名称" v-model.trim="name"
                @keyup.enter.native="loadRoles(); messageAlert()" suffix-icon="el-icon-search" maxlength="20">
            </el-input>
            <!-- 一系列按钮 -->
            <el-button type="primary" style="float: left; margin-left: 5px;" @click="loadRoles(); messageAlert()">搜索
            </el-button>
            <el-button type="warning" style="float: left; margin-left: 10px;" @click="name = ''">重置
            </el-button>

            <el-popconfirm title="确定删除该权限吗？" icon-color="red" @confirm="batchDeleteRoles"
                style="float: right;  margin-left: 15px; margin-top:-2px; ">
                <el-button slot="reference" type="danger">批量删除</el-button>
            </el-popconfirm>

            <!-- <el-upload action="http://localhost:9090/" :show-file-list="false" accept="xlsx"
                :on-success="importExcel" style="display: inline-block;float: right;">
                <el-button style="float: right; margin-left: 20px;" type="success">导入<i class="el-icon-folder-add"
                        style="padding-left: 5px;"></i></el-button>
            </el-upload>


            <el-button style="float: right; margin-left: 20px;" type="info" @click="exportExcel()">导出<i
                    class="el-icon-bottom" style="padding-left: 5px;"></i></el-button> -->

            <!--  -->
            <!--  -->
            <el-button style="float: right; margin-left: 40px; " type="primary"
                @click="dialogFormVisible = true; form.flag = '0'">
                新增<i class="el-icon-circle-plus-outline" style="padding-left: 5px;"></i></el-button>
            <!--点击新增跳出来的表单被修改按钮也使用  -->
            <el-dialog title="权限信息" :visible.sync="dialogFormVisible">
                <el-form :model="form" style="margin-left: -60px;">
                    <el-form-item label="名称" :label-width="formLabelWidth" required>
                        <el-input v-model="form.name" autocomplete="off" maxlength="20"
                            style="width: 500px; float: left;"><i slot="prefix" class="el-icon-user-solid"></i>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth" required>
                        <el-input v-model="form.description" autocomplete="off" maxlength="20"
                            style="width: 500px; float: left;"> <i slot="prefix" class="el-icon-user"></i>
                        </el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogFormVisible = false;
                    form.flag === '0' ? submitForm() : updateRole()">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 菜单分配 -->
            <el-dialog title="菜单分配" :visible.sync="menuDialogVisible">
                <el-tree :data="meanData" 
                show-checkbox 
                node-key="id" 
                :props="props"
                :default-expanded-keys="expends"
                :default-checked-keys="checks"
                ref="tree">
                    <span class = "custom-tree-node" slot-scope = " { node, data }">
                        <span><i :class="data.icon"></i>{{data.name}}</span>
                        <!-- 去除报错never used -->
                        <span :class="node.id"></span>
                    </span>
                </el-tree>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="menuDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="menuDialogVisible = false;setRoleMenu()">确 定</el-button>
                </div>
            </el-dialog>
        </div>

        <div style="height: 90%;padding-top: 0px;padding-bottom: 5px;margin-top: 10px;">
            <!-- 表格 -->
            <el-table :data="tableData" border stripe :header-cell-class-name="headerStyle" v-loading="loading"
                @selection-change="handSelectChange">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="id" label="ID" width="200"></el-table-column>
                <el-table-column prop="name" label="名称" width=""></el-table-column>
                <el-table-column prop="description" label="权限" width=""></el-table-column>
                <el-table-column prop="flag" label="唯一标识" width=""></el-table-column>
                <el-table-column label="操作" width="250">

                    <!--slot-scope="scope"一个添加条件 叫做插槽;  -->
                    <template slot-scope="scope">
                        <el-button type="text" @click="selectMenu(scope.row.id)">分配菜单
                        </el-button>
                        <el-button type="text" @click="dialogFormVisible = true; fillRoleData(scope.row)">编辑
                        </el-button>
                        <!-- 删除按钮，弹出框提醒 Popconfirm 气泡确认框，Popover 弹出框不成功-->
                        <el-popconfirm title="确定删除该权限吗？" icon-color="red" @confirm="deleteRole(scope.row.id)">
                            <el-button slot="reference" type="text">删除</el-button>
                        </el-popconfirm>
                    </template>

                </el-table-column>
            </el-table>
        </div>

        <div class="block" style="padding: 5px;margin-bottom: -10px;padding-left: 380px;">
            <span class="demonstration"></span>
            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                :page-sizes="[5, 8, 12, 15]" :page-size="8" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
    </div>

</template>

<script>
export default {
    name: 'Role',
    data() {
        return {
            tableData: [],//页面数据
            total: 0,//页面大小
            pageNum: 1,//页码
            pageSize: 8,//页大小

            //默认菜单设置
            checks:[],
            expends:[],

            //关键字查询
            name: '',
            //表格加载图片
            loading: true,

            tableRowClassName: 'tableRowClassName',

            props: {
                label: 'name',
            },

            // 弹出框提醒
            visible: false,

            // 新增表单信息
            dialogFormVisible: false,
            menuDialogVisible: false,
            form: {
                flag: '0',//如果是0点击表单就是添加方法,如果是1就是修改方法
                name: '',
                description: '',
            },
            formLabelWidth: '200px',

            roleId:0,

            //菜单分配
            meanData: [],

        }
    },

    methods: {
        handleSizeChange(val) {
            this.pageSize = val;
            this.loadRoles();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.loadRoles();
        },
        headerStyle({ row, column, rowIndex, columnIndex }) {
            return 'tableStyle'
        },
        //获得后台users数据
        loadRoles() {
            // 获得数据之前加载加载页面
            const that = this;
            that.loading = true;
            this.$axios.get('/role/pageRoles', {
                params: {
                    pageNum: that.pageNum,
                    pageSize: that.pageSize,
                    name: that.name,
                }
            })
                .then(function (response) {
                    //获得数据之后取消加载页面 
                    that.loading = false;
                    that.tableData = response.data.roles;
                    that.total = response.data.total;
                })
                .catch(function (error) {
                    console.log(error);
                })
                .then(function () {
                    // always executed
                });
        },
        // 消息提醒方法
        messageAlert() {
            this.$message({
                message: '查询成功！',
                type: 'success',
                duration: 1600
            });
        },
        messageAlert2() {
            this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1600
            });
        },
        messageAlert3() {
            this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1600
            });
        },

        //多选处理
        handSelectChange(val) {
            // 把选择的数字赋值data
            this.multipleSelection = val;
        },

        // 批量删除处理
        batchDeleteRoles() {
            let ids = this.multipleSelection.map(v => v.id);
            const that = this;
            that.loading = true;
            // delet只可以传递一个值，不可以传递对象数组
            this.$axios.post('/role/batchDeleteRoles', {
                ids: ids
            })
                .then(function (response) {
                    that.loadRoles();
                    that.messageAlert3();
                })
                .catch(function (error) {
                    console.log(error);
                })
        },
        //提交表单
        submitForm() {
            const that = this;
            that.loading = true;
            this.$axios.post('/role/save', {
                name: that.form.name,
                description: that.form.description,
            })
                .then(function (response) {
                    //重新加载数据
                    that.loadRoles();
                    that.messageAlert2();
                    // 清除数据
                    that.form.name = '';
                    that.form.description = '';
                })
                .catch(function (error) {
                    console.log(error);
                })
        },

        // 删除用户
        deleteRole(id) {
            // 获得数据之前加载加载页面
            const that = this;
            that.loading = true;
            this.$axios.delete('/role/deleteRole', {
                params: {
                    id: id
                }
            })
                .then(function (response) {
                    that.loadRoles();
                    that.messageAlert3();
                })
                .catch(function (error) {
                    console.log(error);
                })
        },

        fillRoleData(role) {
            this.form.name = role.name;
            this.form.description = role.description;
            this.form.flag = '1';//提交表单为修改操作
            this.form.id = role.id;
        },

        updateRole() {
            const that = this;
            that.loading = true;
            this.$axios.post('/role/update', {
                name: that.form.name,
                description: that.form.description,
                id: that.form.id
            })
                .then(function (response) {
                    //重新加载数据
                    that.loadRoles();
                    that.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1600
                    });
                    // 清除数据
                    that.form.name = '';
                    that.form.description = '';

                    // localStorage.setItem("role", JSON.stringify(this.role));
                })
                .catch(function (error) {
                    console.log(error);
                })
                .then(function () {
                    // always executed
                });
        },

        //打开菜单
        selectMenu(roleId) {
            this.roleId = roleId;
            this.expends = this.meanData.map(v => v.id)
            let that = this;

            this.$axios.get('role/roleMenu/'+that.roleId)
                .then(function (response) {
                    //获得数据之后取消加载页面 
                    that.checks = response.data.data;
                })
                .catch(function (error) {
                    console.log(error);
                })

            this.$axios.get('/menu/menus')
                .then(function (response) {
                    //获得数据之后取消加载页面 
                    that.meanData = response.data.data;
                })
                .catch(function (error) {
                    console.log(error);
                })
                .then(function () {
                    // always executed
                });
            

            this.menuDialogVisible = true;
        },
        //提交分配菜单
        setRoleMenu(){
            let that = this;
            this.$axios.post('/role/roleMenu/'+that.roleId,{
                menuIds: that.$refs.tree.getCheckedKeys(),
            })
                .then(function (response) {
                    if(response.data.code === '200'){
                        that.$message.success("分配成功");
                    }else{
                        that.$message.error("分配失败");
                    }
                })
                .catch(function (error) {
                    console.log(error);
                })
        }   
    },


    created() {
        //以下代码也可以封装在函数中，在其他地方调用
        // 然而问题是出来了this.tableData因为用了 function 函数 的原因，
        // 在函数里面，this是指向函数本身，已经不是外部的默认this了
        this.loadRoles();
    },
}
</script>

<style>
.tableStyle {
    background-color: rgb(236, 236, 236) !important;
    color: rgb(0, 0, 0);
    font-weight: 500;
    font-size: medium;
}
</style>